#!/usr/bin/env python
# encoding: utf-8
'''
@author: Excelsiorly
@license: (C) Copyright 2022, All Rights Reserved.
@contact: excelsiorly@qq.com
@file: 209. 长度最小的子数组.py
@time: 2022/3/4 12:15
@desc: https://leetcode-cn.com/problems/minimum-size-subarray-sum/
> 给定一个含有n个正整数的数组和一个正整数 target 。
找出该数组中满足其和 ≥ target 的长度最小的 连续子数组[numsl, numsl+1, ..., numsr-1, numsr] ，并返回其长度。如果不存在符合条件的子数组，返回 0 。

1. 左右指针
2. Ot(N), Os(1)

'''
class Solution:
    def minSubArrayLen(self, target: int, nums: List[int]) -> int:
        if not nums: return 0
        n = len(nums)
        if n==1: return 1 if nums[0]>=target else 0
        sum, ans = 0, n+1
        left, right = 0, 0
        while right<n:
            sum += nums[right]
            # 如果窗口内的值大，就缩小左边界
            while sum>=target:
                ans = min(ans, right-left+1)
                sum -= nums[left]
                left += 1
            right += 1
        return 0 if ans==n+1 else ans

if __name__ == '__main__':
    target= 7
    nums = [2, 3, 1, 2, 4, 3]
    res = Solution().minSubArrayLen(target, nums)
    print(res)